package com.zero.client;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;

import com.zero.util.Jdbc;

import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class RegisterView extends JFrame {
	private static final long serialVersionUID = 4L;

	private JLabel lblTitle;
	private JLabel lblUsername;
	private JLabel lblNickname;
	private JLabel lblPassword;
	private JLabel lblConfirmPassword;

	private JTextField textFieldUsername;
	private JTextField textFieldNickname;
	private JPasswordField passwordField;
	private JPasswordField passwordFieldConfirm;

	private JButton btnClear;
	private JButton btnRegister;

	/**
	 * 
	 */
	public RegisterView() {
		setSize(460, 300);
		setLocationRelativeTo(null); // 在屏幕中居中显示
		try {
			setIconImage(ImageIO.read(new File("res/Icon.jpg")));
		} catch (IOException e) {
			SwingUtilities.invokeLater(
					() -> JOptionPane.showMessageDialog(this, "读取图标文件出错", "错误", JOptionPane.ERROR_MESSAGE));
		}
		setTitle("注册");
		setResizable(false);
		init();
		addListener();
		setLayout();
		setVisible(true);
	}

	/**
	 * 
	 * @param name
	 * @param password
	 */
	public RegisterView(String name, String password) {
		this();
		textFieldUsername.setText(name);
		passwordField.setText(password);
	}

	/**
	 * 
	 */
	private void init() {
		lblTitle = new JLabel("欢迎注册");
		lblTitle.setForeground(Color.PINK);
		lblTitle.setFont(new Font("黑体", Font.BOLD, 20));
		lblTitle.setHorizontalAlignment(SwingConstants.CENTER);

		lblUsername = new JLabel("用 户 名：");
		lblUsername.setFont(new Font("仿宋", Font.PLAIN, 12));
		lblNickname = new JLabel("昵    称：");
		lblNickname.setFont(new Font("仿宋", Font.PLAIN, 12));
		lblPassword = new JLabel("密    码：");
		lblPassword.setFont(new Font("仿宋", Font.PLAIN, 12));
		lblConfirmPassword = new JLabel("密码确认：");
		lblConfirmPassword.setFont(new Font("仿宋", Font.PLAIN, 12));

		textFieldUsername = new JTextField();
		textFieldNickname = new JTextField();
		passwordField = new JPasswordField();
		passwordFieldConfirm = new JPasswordField();

		btnClear = new JButton("清空");
		btnClear.setFont(new Font("楷体", Font.BOLD, 16));
		btnClear.setForeground(Color.MAGENTA);
		btnRegister = new JButton("注册");
		btnRegister.setFont(new Font("楷体", Font.BOLD, 16));
		btnRegister.setForeground(Color.MAGENTA);

	}

	/**
	 * 
	 */
	private void addListener() {
		textFieldUsername.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					textFieldNickname.grabFocus();
				}
			}
		});

		textFieldNickname.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					passwordField.grabFocus();
				}
			}
		});

		passwordField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					passwordFieldConfirm.grabFocus();
				}
			}
		});

		passwordFieldConfirm.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					register();
				}
			}
		});

		btnClear.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				clear();
			}
		});

		btnRegister.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				register();
			}
		});
	}

	/**
	 * 
	 */
	private void setLayout() {
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
				.createSequentialGroup().addContainerGap()
				.addGroup(groupLayout
						.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
								.addComponent(btnClear, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(ComponentPlacement.RELATED, 231, Short.MAX_VALUE)
								.addComponent(btnRegister, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE))
						.addComponent(lblTitle, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE)
						.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
								.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
										.addComponent(lblPassword, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)
										.addComponent(lblUsername, GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE)
										.addComponent(lblConfirmPassword, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE,
												62, Short.MAX_VALUE)
										.addComponent(lblNickname, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE))
								.addPreferredGap(ComponentPlacement.RELATED)
								.addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(passwordField)
										.addGroup(groupLayout.createSequentialGroup()
												.addComponent(textFieldUsername, GroupLayout.DEFAULT_SIZE, 325,
														Short.MAX_VALUE)
												.addPreferredGap(ComponentPlacement.RELATED))
										.addComponent(passwordFieldConfirm)
										.addGroup(groupLayout.createSequentialGroup()
												.addComponent(textFieldNickname, GroupLayout.DEFAULT_SIZE, 359,
														Short.MAX_VALUE)
												.addPreferredGap(ComponentPlacement.RELATED)))))
				.addGap(11)));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup().addContainerGap().addComponent(lblTitle).addGap(18)
						.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addGroup(groupLayout.createSequentialGroup().addGap(6).addComponent(lblUsername,
										GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
								.addComponent(textFieldUsername))
						.addGap(18)
						.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addGroup(groupLayout.createSequentialGroup().addGap(6).addComponent(lblNickname,
										GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
								.addComponent(textFieldNickname, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE))
						.addGap(18)
						.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addGroup(groupLayout.createSequentialGroup().addGap(6).addComponent(lblPassword,
										GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
								.addComponent(passwordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE))
						.addGap(18)
						.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addGroup(groupLayout.createSequentialGroup().addGap(6).addComponent(lblConfirmPassword,
										GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
								.addComponent(passwordFieldConfirm))
						.addGap(18)
						.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(btnClear, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
								.addComponent(btnRegister, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE))
						.addGap(17)));
		getContentPane().setLayout(groupLayout);
	}

	/**
	 * 
	 */
	private void clear() {
		textFieldUsername.setText("");
		textFieldNickname.setText("");
		passwordField.setText("");
		passwordFieldConfirm.setText("");
		textFieldUsername.grabFocus();
	}

	/**
	 * 
	 */
	private void register() {
		String username = textFieldUsername.getText();
		String nickname = textFieldNickname.getText();
		String password = new String(passwordField.getPassword());

		if (username.isBlank()) {
			SwingUtilities.invokeLater(
					() -> JOptionPane.showMessageDialog(this, "请输入用户名", "提示消息", JOptionPane.INFORMATION_MESSAGE));
			textFieldUsername.grabFocus();
			return;
		}
		if (password.isBlank()) {
			SwingUtilities.invokeLater(
					() -> JOptionPane.showMessageDialog(this, "请输入密码", "提示消息", JOptionPane.INFORMATION_MESSAGE));
			passwordField.grabFocus();
			return;
		}
		if (username.length() > 15 || nickname.length() > 15) {
			SwingUtilities.invokeLater(
					() -> JOptionPane.showMessageDialog(this, "用户名或昵称过长", "提示消息", JOptionPane.INFORMATION_MESSAGE));
			textFieldUsername.grabFocus();
			return;
		}
		if (password.length() < 6 || password.length() > 12) {
			SwingUtilities.invokeLater(
					() -> JOptionPane.showMessageDialog(this, "密码的长度为6-12", "提示消息", JOptionPane.INFORMATION_MESSAGE));
			passwordField.grabFocus();
			return;
		}
		if (!new String(passwordFieldConfirm.getPassword()).equals(password)) {
			SwingUtilities.invokeLater(
					() -> JOptionPane.showMessageDialog(this, "两次输入的密码不同", "提示消息", JOptionPane.INFORMATION_MESSAGE));
			passwordField.setText("");
			passwordFieldConfirm.setText("");
			passwordField.grabFocus();
			return;
		}

		try {
			Jdbc.getConnection();
			String sql = "select * from user";
			List<Map<String, Object>> list = Jdbc.query(sql);
			for (Map<String, Object> user : list) {
				if (username.equals(user.get("name"))) {
					SwingUtilities.invokeLater(
							() -> JOptionPane.showMessageDialog(this, "该用户名已存在！", "提示消息", JOptionPane.WARNING_MESSAGE));
					textFieldUsername.setText(username + "_1");
					return;
				}
			}

			sql = "insert into user(name,nickname,password) values(?,?,?)";
			int flg = Jdbc.update(sql, username, nickname, password);
			Jdbc.closeConnection();
			if (flg > 0) {
				int result = JOptionPane.showConfirmDialog(this, "恭喜您，注册成功！\n是否登录？", "提示消息", JOptionPane.YES_NO_OPTION,
						JOptionPane.INFORMATION_MESSAGE);
				if (result == JOptionPane.OK_OPTION) {
					this.dispose();
					EventQueue.invokeLater(() -> {
						new LoginView(username);
					});
				} else {
					System.exit(0);
				}
			}
		} catch (IOException e) {
			SwingUtilities.invokeLater(() -> {
				int result = JOptionPane.showOptionDialog(this, "加载配置信息出错！", "错误消息", JOptionPane.DEFAULT_OPTION,
						JOptionPane.ERROR_MESSAGE, null, null, null);
				if (result == JOptionPane.OK_OPTION || result == JOptionPane.CLOSED_OPTION) {
					System.exit(1);
				}
			});
		} catch (ClassNotFoundException e) {
			SwingUtilities.invokeLater(() -> {
				int result = JOptionPane.showOptionDialog(this, "驱动类未找到！", "错误消息", JOptionPane.DEFAULT_OPTION,
						JOptionPane.ERROR_MESSAGE, null, null, null);
				if (result == JOptionPane.OK_OPTION || result == JOptionPane.CLOSED_OPTION) {
					System.exit(1);
				}
			});
		} catch (SQLException e) {
			SwingUtilities.invokeLater(() -> {
				int result = JOptionPane.showOptionDialog(this, "获取数据库连接失败！\n可能是用户名或密码错误", "错误消息",
						JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
				if (result == JOptionPane.OK_OPTION || result == JOptionPane.CLOSED_OPTION) {
					System.exit(1);
				}
			});
		}
	}
}
